package com.cxgk.app.cxgkdemo.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cxgk.app.cxgkdemo.R;
import com.cxgk.app.cxgkdemo.activity.AddCarActivity;
import com.cxgk.app.cxgkdemo.activity.SearchResultActivity;
import com.cxgk.app.cxgkdemo.adapter.CarListAdapter;
import com.cxgk.app.cxgkdemo.bean.Car;
import com.cxgk.app.cxgkdemo.bean.Page;
import com.cxgk.app.cxgkdemo.listener.OnItemChildViewClickListener;
import com.cxgk.app.cxgkdemo.logic.BaseModel;
import com.cxgk.app.cxgkdemo.recycleviewdivider.HorizontalDividerItemDecoration;
import com.cxgk.app.cxgkdemo.utils.Constants;
import com.cxgk.app.cxgkdemo.utils.SweetAlertDialogFactory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huang.app.swiperecyclerview.Closeable;
import com.huang.app.swiperecyclerview.OnSwipeMenuItemClickListener;
import com.huang.app.swiperecyclerview.SwipeMenu;
import com.huang.app.swiperecyclerview.SwipeMenuCreator;
import com.huang.app.swiperecyclerview.SwipeMenuItem;
import com.huang.app.swiperecyclerview.SwipeMenuRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.pedant.SweetAlert.SweetAlertDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by lenovo on 2016/12/21.
 */

public class CarListFragment extends BaseFragment implements View.OnClickListener, OnItemChildViewClickListener {
    SwipeRefreshLayout srl_layout;
    SwipeMenuRecyclerView rv_list;
    CarListAdapter mAdapter;
    LinearLayoutManager mLayoutManager;
    boolean smenuOpenAll = false;//编辑按钮展开侧滑菜单的控制
    Page mPage;

    private SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.swipe_recyclerview_width);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext())
                        .setBackgroundDrawable(R.drawable.selector_red)
                        .setImage(R.mipmap.icon_del)
                        .setText("删除") // 文字，还可以设置文字颜色，大小等。。
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。

                SwipeMenuItem editItem = new SwipeMenuItem(getContext())
                        .setBackgroundDrawable(R.drawable.selector_orange)
                        .setImage(R.mipmap.icon_edit)
                        .setText("编辑") // 文字，还可以设置文字颜色，大小等。。
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(editItem);// 添加一个按钮到右侧侧菜单。
            }
        }
    };
    private OnSwipeMenuItemClickListener mOnSwipeMenuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView#RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。

            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION && menuPosition == 0) {
                delItem(adapterPosition);
            } else if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION && menuPosition == 1) {
                Car car = mAdapter.getItem(adapterPosition);
                Intent intent = new Intent(getActivity(), SearchResultActivity.class);
                intent.putExtra(Constants.KEY_DEFAULE, car.getCarType());
                intent.putExtra(Constants.KEY_OBJ1, car.getCarNum());
                startActivity(intent);
            }

        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = new Page();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_car_list, null);
        view.findViewById(R.id.iv_add).setOnClickListener(this);
        view.findViewById(R.id.iv_edit).setOnClickListener(this);
        srl_layout = (SwipeRefreshLayout) view.findViewById(R.id.srl_layout);
        srl_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPage.setPageIndex(1);
                mPage.setRefreshAble(true);
                loadData();
            }
        });
        rv_list = (SwipeMenuRecyclerView) view.findViewById(R.id.rv_list);
        rv_list.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        // 设置菜单创建器。
        rv_list.setSwipeMenuCreator(mSwipeMenuCreator);
        // 设置菜单Item点击监听。
        rv_list.setSwipeMenuItemClickListener(mOnSwipeMenuItemClickListener);
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        rv_list.setLayoutManager(mLayoutManager);
        rv_list.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).colorResId(R.color.list_divider).sizeResId(R.dimen.list_divier).build());
        // TODO: 2016/12/21 分页
        //        rv_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
        //
        //            @Override
        //            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        //                super.onScrolled(recyclerView, dx, dy);
        //                if (!mPage.isRefreshAble()) {
        //                    Snackbar.make(rv_list, "已加载全部", Snackbar.LENGTH_SHORT).show();
        //                } else if (!ViewCompat.canScrollVertically(rv_list, 1) && mPage.isRefreshAble()) {
        //                    mPage.setPageIndex(mPage.getPageIndex() + 1);
        //                    loadData();
        //                }
        //
        //            }
        //        });
        return view;
    }

    //    @Override
    //    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    //        super.onViewCreated(view, savedInstanceState);
    //        srl_layout.post(new Runnable() {
    //            @Override
    //            public void run() {
    //                loadData();
    //            }
    //        });
    //    }

    @Override
    public void onResume() {
        super.onResume();
        srl_layout.post(new Runnable() {
            @Override
            public void run() {
                mPage.setPageIndex(1);
                mPage.setRefreshAble(true);
                loadData();
            }
        });
    }

    /**
     * 数据加载
     */
    private void loadData() {
        try {
            JSONObject object = new JSONObject();
            object.put("CarType", "");
            object.put("CarNum", "");
            object.put("page", mPage.getPageIndex());
            object.put("rows", mPage.getPageSize());
            Call<BaseModel> call = mRestClient.getRectService().httpPost(Constants.DATA_TYPE_SEARCH, object.toString());
            call.enqueue(new Callback<BaseModel>() {
                @Override
                public void onResponse(Call<BaseModel> call, Response<BaseModel> response) {
                    if (response.body().success()) {
                        if (response.body().Items.size() > 0) {
                            Gson gson = new Gson();
                            ArrayList<Car> cars = gson.fromJson(gson.toJson(response.body().Items), new TypeToken<ArrayList<Car>>() {
                            }.getType());
                            if (mPage.getPageIndex() != 1 && cars.size() < mPage.getPageSize()) {
                                mPage.setRefreshAble(false);
                            }
                            if (mAdapter != null) {//不等于空 追加或者更新数据
                                if (mPage.getPageIndex() != 1) {
                                    mAdapter.appendData(cars);
                                } else {
                                    mAdapter.refreshData(cars);
                                }
                            } else {//为空 创建适配器
                                mAdapter = new CarListAdapter(cars, CarListFragment.this);
                                rv_list.setAdapter(mAdapter);
                            }
                        } else {
                            SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.WARNING_TYPE).setContentText("未查询到数据").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                }
                            }).show();
                        }
                    } else {
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(response.body().ResultText).show();
                    }
                    srl_layout.setRefreshing(false);
                }

                @Override
                public void onFailure(Call<BaseModel> call, Throwable t) {
                    t.printStackTrace();
                    srl_layout.setRefreshing(false);
                    SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(getString(R.string.net_error_n)).show();
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                Intent intent = new Intent(getActivity(), AddCarActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_edit:
                if (mAdapter != null) {
                    rv_list.smoothOpenRightMenu(mLayoutManager.findFirstCompletelyVisibleItemPosition());
                }
                break;
        }
    }

    /**
     * list的item点击事件
     *
     * @param id
     * @param position
     */
    @Override
    public void onItemChildViewClickListener(int id, int position) {
        Car car = mAdapter.getItem(position);
        Intent intent = new Intent(getActivity(), SearchResultActivity.class);
        intent.putExtra(Constants.KEY_DEFAULE, car.getCarType());
        intent.putExtra(Constants.KEY_OBJ1, car.getCarNum());
        startActivity(intent);
    }

    /**
     * 删除数据
     */
    private void delItem(final int position) {
        Car car = mAdapter.getItem(position);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("CarType", car.getCarType());
            jsonObject.put("CarNum", car.getCarNum());
            Call<BaseModel> call = mRestClient.getRectService().httpPost(Constants.DATA_TYPE_DEL, jsonObject.toString());
            mLoadingDialog.show();
            call.enqueue(new Callback<BaseModel>() {
                @Override
                public void onResponse(Call<BaseModel> call, Response<BaseModel> response) {
                    mLoadingDialog.dismiss();
                    if (response.body().success()) {
                        mAdapter.removeItem(position);
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.SUCCESS_TYPE).setContentText("已删除").show();
                    } else {
                        SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(response.body().ResultText).show();
                    }
                }

                @Override
                public void onFailure(Call<BaseModel> call, Throwable t) {
                    t.printStackTrace();
                    mLoadingDialog.dismiss();
                    SweetAlertDialogFactory.build(getContext(), SweetAlertDialog.ERROR_TYPE).setContentText(getString(R.string.net_error_n)).show();
                }

            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
